package test.threads.queue.unstressed.impl;

import java.util.concurrent.ConcurrentLinkedQueue;

import test.threads.queue.unstressed.IBoundedQueueFactory;
import test.threads.queue.unstressed.IQueue;

/**
 * Самый базовый вариант, адаптер {@link java.util.concurrent.ConcurrentLinkedQueue} к интерфейсу IQueue.
 *
 * @author cheremin
 * @since 22.09.11,  13:09
 */
public class CLQWrapperQueue<T> implements IQueue<T> {

    private final ConcurrentLinkedQueue<T> queue;
    private final int size;

    public CLQWrapperQueue( final int size ) {
        this.queue = new ConcurrentLinkedQueue<T>();
        this.size = size;
    }

    @Override
    public void enqueue( final T item ) throws InterruptedException {
        while ( queue.size() >= size ) {
        }
        queue.add( item );
    }

    @Override
    public T dequeue() throws InterruptedException {
        while ( true ) {
            final T event = queue.poll();
            if ( event != null ) {
                return event;
            }
        }
    }

    @Override
    public int size() {
        return queue.size();
    }

    @SuppressWarnings( "unchecked" )
    public static <T> IBoundedQueueFactory<T, CLQWrapperQueue<T>> factory() {
        return FACTORY;
    }

    public static final IBoundedQueueFactory FACTORY = new IBoundedQueueFactory<Object, CLQWrapperQueue<Object>>() {
        @Override
        public CLQWrapperQueue<Object> create( final int size ) {
            return new CLQWrapperQueue<Object>( size );
        }

        @Override
        public String toString() {
            return "CLQWrapperFactory";
        }
    };
}
